<script setup>
import {ref, computed, watch, onMounted} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from "element-plus"
import axios from "axios"
import { useRoute } from 'vue-router'

const router = useRouter()
const route=useRoute()


// 初始化时获取 categoryId 并加载数据
const loadCategoryData = (categoryId) => {
  if (categoryId) {
    axios.get(`/category/getCategoryById/${categoryId}`).then((res) => {
      form.value =  {
        ...res.data,
        subCategories: Array.isArray(res.data.subCategories)
            ? res.data.subCategories
            : JSON.parse(res.data.subCategories || '[]')
      };
    }).catch(error => {
      console.error("加载品类数据失败", error)
    })
  }
}

const categoryId=ref(route.query.categoryId);

// 表单数据
const form = ref({
  categoryId: "",
  categoryName: '',
  sortOrder: 1,
  subCategories: [], // 确保这是数组
  description: ''
})



// 监听 categoryId 的变化
watch(() => route.query.categoryId, (newValue) => {
  categoryId.value = newValue
  loadCategoryData(newValue)
})
// 子品类输入框的值
const subCategoryInput = ref('')

// 添加子品类
const addSubCategory = () => {
  const trimmedValue = subCategoryInput.value.trim()
  if (trimmedValue) {
    form.value.subCategories.push(trimmedValue)
    subCategoryInput.value = '' // 清空输入框
  }
}

// 删除子品类
const removeSubCategory = (index) => {
  form.value.subCategories.splice(index, 1)
}

// 提交表单
const submitForm = () => {
  if (form.value.subCategories.length === 0) {
    ElMessage.error('请至少添加一个子品类')
    return
  }
 if(categoryId){
   axios.put(`/category/updateCategory/${categoryId.value}`,form.value).then((res)=>{
     router.push('/category')
     ElMessage.success(res.data)
   })
 }else {
   axios.post(`/category/addCategory`,form.value).then((res)=>{
     router.push('/category')
     ElMessage.success(res.data)
   })
 }
}


// 取消
const cancel = () => {
  router.back()
}
onMounted(() => {
  loadCategoryData(categoryId.value)
})
</script>

<template>
  <div class="category-edit">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>新增品类</span>
        </div>
      </template>

      <el-form :model="form" label-width="100px">
        <!-- 品类名称 -->
        <el-form-item label="品类名称：" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入品类名称" style="width: 300px" />
        </el-form-item>

        <!-- 修改品类顺序列 -->
        <el-form-item label="品类顺序：" prop="sortOrder">
          <div class="sort-container">
            <el-input-number
                v-model="form.sortOrder"
                :min="1"
                :max="100"
            />

          </div>
        </el-form-item>

        <!-- 子品类 -->
        <el-form-item label="子品类：" prop="subCategories">
          <div class="sub-category-container">
            <div class="sub-category-input">
              <el-input
                  v-model="subCategoryInput"
                  placeholder="请输入子品类名称"
                  style="width: 200px; margin-right: 10px"
                  @keyup.enter="addSubCategory"
              />
              <el-button
                  type="primary"
                  :disabled="!subCategoryInput.trim()"
                  @click="addSubCategory"
              >
                + 添加
              </el-button>
              <span class="sub-tip">最少添加一个子类</span>
            </div>

            <div class="sub-category-tags">
              <el-tag
                  v-for="(item, index) in form.subCategories"
                  :key="index"
                  closable
                  @close="removeSubCategory(index)"
              >
                {{ item }}
              </el-tag>
            </div>
          </div>
        </el-form-item>

        <!-- 品类描述 -->
        <el-form-item label="品类描述：" prop="description">
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="请输入品类描述"
              style="width: 500px"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>

.category-edit {
  padding: 20px;
}

.box-card {
  width: 800px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

/* 隐藏数字输入框的上下箭头 */
.sort-container :deep(.el-input-number__decrease),
.sort-container :deep(.el-input-number__increase) {
  display: none;
}

/* 调整数字输入框样式 */
.sort-container :deep(.el-input-number .el-input__wrapper) {
  padding-right: 15px;
}

.sub-category-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.sub-category-input {
  display: flex;
  align-items: center;
}

.sub-tip {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}

.sub-category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>
